/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.flash.util;
import flash.display.InteractiveObject;
import flash.events.MouseEvent;
import hapi.physics.Time;
import haxe.Timer;

class CallbackButton {

	var button:InteractiveObject;
	var handlesHolding:Bool;
	var callbackFunc:Void->Void;
	var startHoldIntervalAfter:Time;
	var holdIntervalStep:Time;
	var holdTimer:Timer;
	
	public function new(button:InteractiveObject, callOnClick:Void->Void) {
		this.button = button;
		this.handlesHolding = false;
		this.callbackFunc = callOnClick;
		button.addEventListener( MouseEvent.CLICK, onClick );
	}
	
	public static function redirect(button:InteractiveObject, callOnClick:Void->Void):Void {
		button.addEventListener( MouseEvent.CLICK, function(e) { callOnClick(); } );
	}
	
	public function allowHold(?afterSeconds = 0.5, ?clickPerSecond = 5) {
		if (!handlesHolding) {
			button.removeEventListener(MouseEvent.CLICK, onClick);
			button.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			button.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			handlesHolding = true;
		}
		startHoldIntervalAfter = new Time(afterSeconds);
		holdIntervalStep = new Time(1 / clickPerSecond);
	}
	
	function onClick(e) {
		callbackFunc();
	}
	
	function onMouseDown(e) {
		button.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		callbackFunc();
		if (holdTimer != null) holdTimer.stop();
		holdTimer = new Timer(startHoldIntervalAfter.millis);
		holdTimer.run = startHold;
	}
	
	function onMouseUp(e) {
		button.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		stopHold();
	}
	
	function onHold() {
		callbackFunc();
	}
	
	function startHold() {
		if (holdTimer != null) holdTimer.stop();
		holdTimer = new Timer(holdIntervalStep.millis);
		holdTimer.run = onHold;
	}
	
	function stopHold() {
		holdTimer.stop();
		holdTimer = null;
	}
	
	public function show() {
		button.visible = true;
	}
	
	public function hide() {
		button.visible = false;
	}
}
